#include <bits/stdc++.h>

using namespace std;

const int MAXN = 1e6 + 10;
int t, n, d;
int a[MAXN], b[MAXN * 2];

int gcd(int x, int y) {
    return y == 0 ? x : gcd(y, x % y);
}

int main() {
#ifdef LOCAL
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
#endif
    ios::sync_with_stdio(false), cin.tie(0);
    cin >> t;
    while (t--) {
        cin >> n >> d;
        for (int i = 0; i < n; i++) cin >> a[i];

        for (int i = 0; i <= n * 2 + 1; i++) b[i] = 0;

        int k = gcd(n, d), num = n / k, flag = true;
        for (int i = 0; i < k;i++) {
            if (!flag) break;
            int pos = i;
            b[pos] = a[pos];
            for (int j = 1; j < num * 2; j++) {
                int nxt = (pos + d) % n;
                if (a[nxt]) b[nxt] = b[pos] + 1;
                if (b[nxt] >= num) {
                    flag = false;
                    break;
                }
                pos = nxt;
            }
        }

        if (!flag) {
            cout << -1 << endl;
            continue;
        }

        int ans = 0;
        for (int i = 0; i < n * 2; i++) ans = max(ans, b[i]);
        cout << ans << endl;
    }
    return 0;
}